package com.yuexun.concurrency.sync;

import com.yuexun.concurrency.annoations.ThreadSafe;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
@ThreadSafe
public class SyncExample {
    //修饰一个代码块
    public void test1(int j){
        synchronized (this){
            for (int i = 0;i<10;i++){
                log.info("test1 - {} - {}",j,i);
            }
        }
    }
    //修饰一个方法
    public synchronized void test2(int j) {
        for (int i = 0; i < 10; i++) {
            log.info("test2 - {} - {}",j, i);
        }
    }

    public static void main(String[] args) {
        SyncExample syncExample = new SyncExample();
        SyncExample syncExample2 = new SyncExample();
        //声明一个线程池,下面的执行就相当于分别开启了2个线程去执行,并发执行
        ExecutorService executorService = Executors.newCachedThreadPool();
        //通过线程池模拟了同一个对象同时调用了两个线程
        executorService.execute(()->{
            syncExample.test2(1);;
        });
        executorService.execute(()->{
            syncExample2.test2(2);;
        });
    }
}
